<?php

namespace App\Http\Controllers\Admin;

use App\Admin\Admin;
use Illuminate\Support\Facades\Input;
use Validator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;

class LoginController extends Controller
{
    public function login(Request $request)
    {
        if ($request->isMethod('post')) {
            if (strtoupper($request->code) != strtoupper($request->codey)) {
                return back()->with('msg', '验证码错误');
            }
            $res= DB::table('admin')->where([['username',$request->username],['password',md5($request->password)]])->get();
            if (!$res->all()) {
                return back()->with('msg', '用户名或密码错误');
            }
            session(['admin'=>$res]);
            // 获取用户角色状态
            $status =DB::table('admin')->where('username',$request->username)->get()->toArray();
            if ($status[0]->status == '0') {
                return back()->with('msg', '您被禁用，请联系管理员');
            }
            return redirect('admin/index');
        }
                return view('admin/login');

    }
    public function quit()
    {
        session(['admin'=>null]);
        return redirect('admin/login');
    }

    public function pass()
    {
        $admin = session()->get('admin');
        $admin = $admin[0];
        return view('admin/password',compact('admin'));
    }

    public function changedit()
    {
        $input = Input::all();
//        dd($input);
        $id = $input['id'];
        $pass = $input['pass'];
        $repass = $input['repass'];
        if($pass != $repass){
            $data = ['status'=>1,
                'msg'=>'你新密码和确认密码不相等',
            ];
            return $data;
    }
        $password = $input['password'];
        $password = md5($password);
        $res =DB::table('admin')->where('password',$password)->get()->toArray();
        if(!$res){
            $data = ['status'=>1,
                'msg'=>'你之前的密码不正确',
            ];
            return $data;
        }
        $pass = md5($pass);
        $ress =DB::table('admin')
            ->where('id',$id)
            ->update([
                'password'=>$pass
            ]);
        if($ress){
            $data = ['status'=>0,
                'msg'=>'密码修改成功',

            ];
        }else{
            $data = [
                'status'=>1,
                'msg'=>'密码修改失败，请重试',
            ];
        }
        return $data;
    }
}
